package com.example.terminalservice.filter;

import com.example.terminalservice.common.CodeEnum;
import com.example.terminalservice.common.Result;
import com.example.terminalservice.exception.MyException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 28142
 * @description 登录验证码过滤器
 * @date 2023/8/13 18:41
 */
@Component
public class CaptchaFilter extends OncePerRequestFilter {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        System.out.println("captcha filter");
        // 如果是登录请求，需要进行验证码校验；否则放行，执行下一个过滤器
        if ("/login".equals(request.getRequestURI())) {
            String code = request.getParameter("code");
            // 获取前端传递的验证码的key
            String captchaKey = request.getParameter("captchaKey");
            System.out.println(captchaKey);
            // 根据验证码的key获取之前生成的验证码
            String captcha = stringRedisTemplate.opsForValue().get(captchaKey);
            System.out.println(captcha);
            if (code == null || !code.equals(captcha)) {
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                PrintWriter writer = response.getWriter();
                writer.write(objectMapper.writeValueAsString(Result.error(CodeEnum.CODE_403)));
                return;
            }
        }
        filterChain.doFilter(request, response);
    }
}
